package kpi.javatraining6.gnatiuk.src.tester;

import java.util.List;

import kpi.javatraining6.gnatiuk.src.tester.inout.Input;
import kpi.javatraining6.gnatiuk.src.tester.readers.ConfigDOMReader;
import kpi.javatraining6.gnatiuk.src.tester.readers.UserDOMParser;
import kpi.javatraining6.gnatiuk.src.tester.readers.UserDOMSaver;
import kpi.javatraining6.gnatiuk.src.tester.user.AdminController;
import kpi.javatraining6.gnatiuk.src.tester.user.User;
import kpi.javatraining6.gnatiuk.src.tester.user.UserController;

/**
 * Class responsible for a authorizing
 */
public class Authorizer {
	private final String ADMIN_NAME;
    private UserController userController;
    private List<User> users;
    private User user;
    
    public Authorizer() {
       users = new UserDOMParser().getUsers();
       ADMIN_NAME = ConfigDOMReader.getInstance().getAdminName();

    }

    public User generateUser() {
        String userName = Input.getInstance().get("Enter the user name");
        String userPassword =(Input.getInstance().get("Enter the user password"));
        user = new User(userName, userPassword);
        if (authenticateUser(user)) {
            return user;
        }
        return null;
    }

    public boolean authenticateUser(User someUser){
        if (users.contains(someUser)) {
            System.out.println("user found");
            if (!checkPassword(someUser)) {
                return false;
            }
        }else {
            acceptNewUser(someUser);
        }
        userController = determineUserController(user);
        return true;
    }

    private void acceptNewUser(User someUser) {
        System.out.println("New user was created");
        UserDOMSaver.getInstance().saveUserProgress(someUser);
        user = someUser;
         users.add(user);
    }

    private boolean checkPassword(User someUser) {
        int userIndex = users.indexOf(someUser);
        if (someUser.getPassword().equals(users.get(userIndex).getPassword())){
            System.out.println("Welcome back!");
            Logger.getInstance().recordUserAction(someUser.getUserName(), "Authentication successful");
            user = users.get(userIndex);
            return true;
        } else {
            System.out.println("Wrong password");
            Logger.getInstance().recordUserAction(someUser.getUserName(), "Authentication failed");
            return false;
        }
    }

    public UserController getUserController() {
        return userController;
    }

    /**
     * Selection of the controller. Case administrator or a simple user controller
     */
    private UserController determineUserController(User user) {
    	if(user.getUserName().equals(ADMIN_NAME)){
    		return new AdminController(user, users);
    	}else{
    		return new UserController(user);
    	}
    }
}
